package com.yxhl.zoume.core.officialcar.presenter;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.BizOrderResponse;
import com.yxhl.protobuf.Location;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.protobuf.OrderRideStatus;
import com.yxhl.protobuf.ServiceType;
import com.yxhl.protobuf.TcpResponse;
import com.yxhl.zoume.R;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.presenter.IPresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.func.map.ZMDrivingRouteOverlay;
import com.yxhl.zoume.core.func.tcp.TcpRequestProvider;
import com.yxhl.zoume.core.officialcar.view.OfficialCarScheduleMapView;
import com.yxhl.zoume.core.specialcar.model.MarkerCategory;
import com.yxhl.zoume.core.specialcar.model.MarkerType;
import com.yxhl.zoume.core.tripsmgmt.presenter.ipresenter.ICommentPresenter;
import com.yxhl.zoume.core.tripsmgmt.view.unit.CommentOnDriverView;
import com.yxhl.zoume.data.http.rest.param.tripsmgnt.CommentDriverParam;
import com.yxhl.zoume.data.http.rest.response.tirps.CommentDriverResponse;
import com.yxhl.zoume.data.tcp.OnChannelListener;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.car.specialcar.SpecialCarPollingUseCase;
import com.yxhl.zoume.domain.interactor.tripsmgmt.CommentDriverUseCase;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.StringUtils;
import com.yxhl.zoume.utils.tcp.TcpService;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import static com.yxhl.protobuf.OrderBizType.OFFICIAL_BUS_TIME;
import static com.yxhl.protobuf.OrderBizType.OFFICIAL_BUS_WAY;

/**
 * Created by sugarya on 16/8/21.
 * TCP 连接 轮询请求
 */
public class OfficialCarScheduleMapPresenter extends BasePresenter implements IPresenter, ICommentPresenter,
        ServiceConnection, RouteSearch.OnRouteSearchListener, AMap.OnMapClickListener {

    private static final int WHAT_TCP_RESPONSE = 1;
    private static final String TAG = "OfficialCarSchedulePre";
    private static final int TCP_REQUEST_PERIOD = 10 * 1000;
    @Inject
    SpecialCarPollingUseCase mSpecialCarPollingUseCase;
    @Inject
    CommentDriverUseCase mCommentDriverUseCase;
    /**
     * 路径规划入口
     */
    private RouteSearch mRouteSearch;
    /**
     * 线路规划图层
     */
    private ZMDrivingRouteOverlay mDrivingRouteOverlay;
    /**
     * 地图操作引用
     */
    private AMap aMap;
    /**
     * 路线是否已经规划
     */
    private boolean isRouteSearched = false;
    private OfficialCarScheduleMapView mOfficialCarScheduleMapView;
    private CommentOnDriverView mCommentOnDriverView;

    /**
     * 上一次网络请求得到的乘车状态,默认为初始化状态
     */
    private int mLastRideStatus = OrderRideStatus.ORIS_DEFAULT_VALUE;

    /**
     * MarkerOptions容器
     */
    private ArrayList<MarkerOptions> mMarkerOptionsList;

    private TcpService.TcpClientController mTcpClientController;

    /**
     * 订单编号
     */
    private String mOrderSerial;

    private OfficialCarHandler mOfficialCarHandler;

    private Timer timer;

    private boolean isMarkShow;


    @Inject
    public OfficialCarScheduleMapPresenter(Context context) {
        super(context);
    }


    private void bindTcpService(final Activity activity) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(activity, TcpService.class);
                activity.bindService(intent, OfficialCarScheduleMapPresenter.this, Context.BIND_AUTO_CREATE);
            }
        }).start();
    }

    public void unbindTcpService(Activity activity) {
        mTcpClientController.closeChannel();
        activity.unbindService(this);
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mTcpClientController = (TcpService.TcpClientController) service;

        mTcpClientController.startTcpConnection(new OnChannelListener() {


            @Override
            public void onChannelActive() {

            }

            @Override
            public void onChannelInactive() {
                LOG.e(TAG, "onChannelInactive");
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
            }

            @Override
            public void onConnectionSuccess() {
                if (timer == null) {
                    LOG.e(TAG, "onConnectionSuccess");
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (!TextUtils.isEmpty(mOrderSerial)) {
                                mTcpClientController.sendTcpRequest(
                                        TcpRequestProvider.getInstance().init(mContext, mOrderSerial)
                                                .getTcpRequest(ServiceType.USER_QUERY_LOC));
                            }
                        }
                    }, 0, TCP_REQUEST_PERIOD);
                }
            }

            @Override
            public void onChannelRead(TcpResponse tcpResponse) {
                if (tcpResponse != null) {
                    LOG.e(TAG, "onChannelRead");


                    boolean isSucc = tcpResponse.getIsSucc();
                    if (isSucc) {
                        BizOrderResponse bizOrderResp = tcpResponse.getBizOrderResp();
                        if (bizOrderResp.getOrderBizType() == OFFICIAL_BUS_WAY || bizOrderResp.getOrderBizType() == OFFICIAL_BUS_TIME) {
                            List<BizOrder> orderFieldsesList = bizOrderResp.getOrderFieldsesList();
                            int orderFieldsesCount = bizOrderResp.getOrderFieldsesCount();
                            mOfficialCarScheduleMapView.renderDataOnSuccess(bizOrderResp);

                            Message msg = mOfficialCarHandler.obtainMessage();
                            msg.obj = bizOrderResp;
                            msg.what = WHAT_TCP_RESPONSE;
                            mOfficialCarHandler.sendMessage(msg);
                        }

                    }
                }
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        LOG.v(TAG, "onServiceDisconnected " + name.getShortClassName());
    }

    public void startPolling(Activity activity, final String orderId) {
        mOrderSerial = orderId;
        mOfficialCarHandler = new OfficialCarHandler(Looper.getMainLooper());

        bindTcpService(activity);
    }

    /**
     * 更新乘车状态
     *
     * @param bizOrderResponse
     */
    public void updateUIByRideStatus(BizOrderResponse bizOrderResponse) {


        if (bizOrderResponse != null) {
            OrderRideStatus rideStatus = bizOrderResponse.getRideStatus();
            LOG.e(TAG, "rideStatus=" + rideStatus);

            switch (rideStatus) {
                //订单预约中,未派车
                case UN_SEND:
                    handleOfficialBusWayRoute(bizOrderResponse);
                    if (mLastRideStatus < OrderRideStatus.UN_SEND_VALUE) {
                        //更新Toolbar
                        mOfficialCarScheduleMapView.setupHeaderStatus(
                                ZouMeApplication.application.getString(R.string.route_detail_no_charter),
                                ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
                        );
                        //弹出ScheduleBar动画
                        mOfficialCarScheduleMapView.startEnterAnimatorForScheduleBar();

                        //更新乘车状态
                        mLastRideStatus = OrderRideStatus.UN_SEND_VALUE;
                    }
                    //司机拒绝接任务,订单状态回滚到未派车
                    else if (mLastRideStatus == OrderRideStatus.UN_TAKEN_VALUE) {
                        //开启ScheduleBar退出动画
                        mOfficialCarScheduleMapView.startExitAnimatorForScheduleBar();
                        //更新ScheduleBar数据
                        mOfficialCarScheduleMapView.updateDataBetweenRideStatus(
                                OrderRideStatus.UN_TAKEN_VALUE,
                                OrderRideStatus.UN_SEND_VALUE,
                                bizOrderResponse.getDriverTel());
                        //更新Toolbar
                        mOfficialCarScheduleMapView.setupHeaderStatus(
                                ZouMeApplication.application.getString(R.string.route_detail_no_charter),
                                ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
                        );
                        //开启ScheduleBar进入动画
                        mOfficialCarScheduleMapView.startEnterAnimatorForScheduleBar();
                        //更新乘车状态
                        mLastRideStatus = OrderRideStatus.UN_SEND_VALUE;
                    }

                    break;
                //订单提交成功,正在派车中
                case UN_TAKEN:
                    handleOfficialBusWayRoute(bizOrderResponse);
                    LOG.e(TAG, "UN_GET_IN");
                    //第一次轮询到该状态时
                    if (mLastRideStatus <= OrderRideStatus.UN_SEND_VALUE) {
                                /*
                                    1.更新DriverIno信息
                                    2.更新Toolbar信息
                                    3.开启过度动画
                                    4.更新乘车状态
                                 */
                        String content = StringUtils.getCalledName(bizOrderResponse.getDriverName()) + " " + bizOrderResponse.getVehicleNo();
                        int judgePoint = (int) bizOrderResponse.getDriverJudgePoint();
                        LOG.e(TAG, "judgePoint=" + judgePoint);
                        mOfficialCarScheduleMapView.setupDriverInfoStatus(content, judgePoint, true, bizOrderResponse.getDriverTel());

                        mOfficialCarScheduleMapView.setupHeaderStatus(
                                ZouMeApplication.application.getString(R.string.route_detail_wait_charter),
                                ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip)
                        );
                        //true,表示由上一个状态过度来的,则需要开启移除上一个状态出现的行程信息栏动画
                        if (mLastRideStatus != OrderRideStatus.ORIS_DEFAULT_VALUE) {
                            mOfficialCarScheduleMapView.startExitAnimatorForScheduleBar();
                        }

                        mOfficialCarScheduleMapView.updateDataBetweenRideStatus(
                                OrderRideStatus.UN_SEND_VALUE,
                                OrderRideStatus.UN_TAKEN_VALUE,
                                bizOrderResponse.getDriverTel());

                        mOfficialCarScheduleMapView.startEnterAnimatorForDriverInfoAndScheduleBar(true);

                        mLastRideStatus = OrderRideStatus.UN_TAKEN_VALUE;
                    }

                    break;
                //乘客上车,行程中
                case TAKEN:
                    handleOfficialBusWayRoute(bizOrderResponse);
                    String runTime = bizOrderResponse.getRunTime();
                    String runDistance = bizOrderResponse.getRunDistance();
                    mOfficialCarScheduleMapView.updateTimeAndDistanceValue(runTime, runDistance);


                    if (mLastRideStatus <= OrderRideStatus.UN_TAKEN_VALUE) {
                        //更新ToolBar
                        mOfficialCarScheduleMapView.setupTitleStatus(
                                ZouMeApplication.application.getString(R.string.route_detail_take_charter)
                        );
                        //更新DriverInfo
                        String content = StringUtils.getCalledName(bizOrderResponse.getDriverName()) + " " + bizOrderResponse.getVehicleNo();
                        int judgePoint = (int) bizOrderResponse.getDriverJudgePoint();
                        Log.e(TAG, "updateUIByRideStatus: judgePoint" + judgePoint);
                        mOfficialCarScheduleMapView.setupDriverInfoStatus(content, judgePoint, true, bizOrderResponse.getDriverTel());

                        if (mLastRideStatus != OrderRideStatus.ORIS_DEFAULT_VALUE) {
                            //退出ScheduleBar动画
                            mOfficialCarScheduleMapView.startExitAnimatorForScheduleBar();
                        } else {
                            mOfficialCarScheduleMapView.startEnterAnimatorForDriverInfoAndScheduleBar(false);
                        }

                        if (bizOrderResponse.getOrderBizType() == OrderBizType.OFFICIAL_BUS_TIME) {
                            //开启时间/里程统计栏
                            mOfficialCarScheduleMapView.startTimeDistanceInfoBarAnimator(true);
                        } else {
                            mOfficialCarScheduleMapView.startTimeDistanceInfoBarAnimator(false);
                        }

                        //更新乘车状态
                        mLastRideStatus = OrderRideStatus.TAKEN_VALUE;
                    }
                    break;
                //已到站,去评论
                case ARRIVED:
                    if (mLastRideStatus <= OrderRideStatus.TAKEN_VALUE) {
                        //更新ToolBar
                        mOfficialCarScheduleMapView.setupHeaderStatus(
                                ZouMeApplication.application.getString(R.string.route_detail_finish_charter),
                                ""
                        );
                        if (mLastRideStatus != OrderRideStatus.ORIS_DEFAULT_VALUE) {
                            //DriverInfo退出动画
                            mOfficialCarScheduleMapView.startExitAnimatorForDriverInfo();
                        }
                        //退出时间,里程统计栏
                        mOfficialCarScheduleMapView.startTimeDistanceInfoBarAnimator(false);
                        //行程结束对话框
                        mOfficialCarScheduleMapView.showArrivalDialog(bizOrderResponse);

                        //更新乘车状态
                        mLastRideStatus = OrderRideStatus.ARRIVED_VALUE;
                    }
                    break;
                //司机未接到,订单失效
//                    case SpecialCarRideStatus.DRIVER_DROP_ORDER:
//                        if (mLastRideStatus <= SpecialCarRideStatus.ARRIVED) {
//                            //设置Toolbar
//                            mOfficialCarScheduleMapView.setupHeaderStatus(
//                                    ZouMeApplication.application.getString(R.string.route_detail_cancel_charter),
//                                    ""
//                            );
//
//                            //显示对话框
//                            mOfficialCarScheduleMapView.showWaitingDialog(ScheduleDialogType.DRIVER_CLOSE_ORDER);
//
//                            //更新乘车状态
//                            mLastRideStatus = SpecialCarRideStatus.DRIVER_DROP_ORDER;
//
//                            stopPolling();
//                        }
//                        break;
//                    //订单关闭,与订单失效互斥
//                    case SpecialCarRideStatus.CLOSE_ORDER:
//                        if (mLastRideStatus <= SpecialCarRideStatus.DRIVER_DROP_ORDER) {
//                            //设置Toolbar
//                            mOfficialCarScheduleMapView.setupHeaderStatus(
//                                    ZouMeApplication.application.getString(R.string.special_car_operation_cancel_trip),
//                                    ""
//                            );
//
//                            //显示对话框
//                            mOfficialCarScheduleMapView.showWaitingDialog(ScheduleDialogType.INVALIDATE_ORDER);
//
//                            //更新乘车状态
//                            mLastRideStatus = SpecialCarRideStatus.CLOSE_ORDER;
//
//                            stopPolling();
//                        }
//                        break;

            }
        }
    }

    /**
     * 更新公务车计时地图覆盖物
     *
     * @param aMap
     * @param LatLngList
     */
    public void refreshOfficialCarTimingMarkersInMap(AMap aMap,
                                                     List<Location> LatLngList) {

        if (isMarkShow) {
            return;
        }
        isMarkShow = true;
        if (aMap != null) {
            //清空地图上所有覆盖物
            aMap.clear();
            if (mMarkerOptionsList == null) {
                mMarkerOptionsList = new ArrayList<>();
            }
            mMarkerOptionsList.clear();

            if (LatLngList != null && LatLngList.size() > 0) {
                for (Location location : LatLngList) {
                    String locType = location.getLocType();
                    String lat = location.getLat();
                    String lng = location.getLng();
                    LOG.e(TAG, "出发 latlng:lat=" + lat + "  lng=" + lng);
                    double latDouble;
                    double lngDouble;
                    try {
                        latDouble = Double.parseDouble(lat);
                        lngDouble = Double.parseDouble(lng);
                    } catch (Exception e) {
                        e.printStackTrace();
                        latDouble = 0;
                        lngDouble = 0;
                    }

                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions
                            .setFlat(true)
                            .draggable(false)
                            .position(new LatLng(latDouble, lngDouble))
                            .icon(
                                    BitmapDescriptorFactory.fromResource(
                                            getMarkerIconResId(MarkerCategory.DEPART, locType))
                            );
                    mMarkerOptionsList.add(markerOptions);
                }
            }

            for (MarkerOptions markerOptions : mMarkerOptionsList) {
                aMap.addMarker(markerOptions);
            }
        }
    }


    /**
     * 更新计程地图覆盖物
     *
     * @param aMap
     * @param LatLngList
     * @param eLatLngList
     */
    public void refreshOfficialCarMileageMarkersInMap(AMap aMap,
                                                      List<Location> LatLngList,
                                                      List<Location> eLatLngList) {
        if (isMarkShow) {
            return;
        }
        isMarkShow = true;

        if (aMap != null) {
            //清空地图上所有覆盖物
            aMap.clear();
            if (mMarkerOptionsList == null) {
                mMarkerOptionsList = new ArrayList<>();
            }
            mMarkerOptionsList.clear();

            if (LatLngList != null && LatLngList.size() > 0) {
                for (Location location : LatLngList) {
                    String locType = location.getLocType();
                    String lat = location.getLat();
                    String lng = location.getLng();
                    LOG.e(TAG, "出发 latlng:lat=" + lat + "  lng=" + lng);
                    double latDouble;
                    double lngDouble;
                    try {
                        latDouble = Double.parseDouble(lat);
                        lngDouble = Double.parseDouble(lng);
                    } catch (Exception e) {
                        e.printStackTrace();
                        latDouble = 0;
                        lngDouble = 0;
                    }

                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions
                            .setFlat(true)
                            .draggable(false)
                            .position(new LatLng(latDouble, lngDouble))
                            .icon(
                                    BitmapDescriptorFactory.fromResource(
                                            getMarkerIconResId(MarkerCategory.DEPART, locType))
                            );
                    mMarkerOptionsList.add(markerOptions);
                }
            }

            if (eLatLngList != null && eLatLngList.size() > 0) {
                for (Location location : eLatLngList) {
                    String locType = location.getLocType();
                    String lat = location.getLat();
                    String lng = location.getLng();
                    LOG.e(TAG, "目的 elatlng:lat=" + lat + "  lng=" + lng);
                    double latDouble;
                    double lngDouble;
                    try {
                        latDouble = Double.parseDouble(lat);
                        lngDouble = Double.parseDouble(lng);
                    } catch (Exception e) {
                        e.printStackTrace();
                        latDouble = 0;
                        lngDouble = 0;
                    }

                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions
                            .setFlat(true)
                            .draggable(false)
                            .anchor(0.5f, 1f)
                            .position(new LatLng(latDouble, lngDouble))
                            .icon(BitmapDescriptorFactory.fromResource(
                                    getMarkerIconResId(MarkerCategory.ARRIVAL, locType)
                            ));
                    mMarkerOptionsList.add(markerOptions);
                }
            }

            // aMap.addMarkers(mMarkerOptionsList, false);
            for (MarkerOptions markerOptions : mMarkerOptionsList) {
                aMap.addMarker(markerOptions);
            }
        }
    }

    /**
     * 获取地图覆盖物对应的图标
     *
     * @param category
     * @param locType
     * @return
     */
    public
    @DrawableRes
    int getMarkerIconResId(int category, String locType) {
        if (!TextUtils.isEmpty(locType)) {
            int markerIconResId;
            switch (locType) {
                case MarkerType.USER:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.ic_shangche_location : R.drawable.ic_xiache_location;
                    break;
                case MarkerType.PARTNER:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.ic_shangche_location : R.drawable.ic_xiache_location;
                    break;
                case MarkerType.CAR:
                    markerIconResId = category == MarkerCategory.DEPART
                            ? R.drawable.ic_kuaiche_tubiao : 0;
                    break;
                default:
                    markerIconResId = 0;
            }
            return markerIconResId;
        }
        return 0;
    }

    @Override
    public void commentOnDriver(String orderId, int starAmount, String commentMessage) {
        CommentDriverParam commentDriverParam = new CommentDriverParam(
                getMobile(),
                getToken(),
                orderId,
                starAmount,
                commentMessage
        );
        mCommentDriverUseCase.execute(commentDriverParam,new ZMSubscriber<CommentDriverResponse>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mCommentOnDriverView.closeCommentOnCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mCommentOnDriverView.renderCommentOnError("");
                    }

                    @Override
                    public void onNext(CommentDriverResponse commentDriverResponse) {
                        super.onNext(commentDriverResponse);
                        if (commentDriverResponse != null) {
                            boolean succ = commentDriverResponse.isSucc();
                            String resultMessage = commentDriverResponse.getResultMessage();
                            if (succ) {
                                mCommentOnDriverView.renderCommentOnSuccess();
                            } else {
                                mCommentOnDriverView.renderCommentOnError(resultMessage);
                            }
                        }
                    }
                });
    }

    public void init(AMap aMap) {
        this.aMap = aMap;
        registerListener();
        mRouteSearch = new RouteSearch(mContext);
        mRouteSearch.setRouteSearchListener(this);
    }

    private void registerListener() {
        aMap.setOnMapClickListener(this);
    }

    private void handleOfficialBusWayRoute(BizOrderResponse bizOrderResponse) {
        if (bizOrderResponse.getOrderBizType() == OFFICIAL_BUS_WAY) {
            calculateOfficialCarRoute(bizOrderResponse);
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    /**
     * 公务车路径规划
     *
     * @param bizOrderResponse
     */
    public void calculateOfficialCarRoute(BizOrderResponse bizOrderResponse) {

        // 0. 线路规划一次就好
//        if (isRouteSearched) {
//            return;
//        }
        //配置线路的起点,终点
        Location selfInfo = bizOrderResponse.getLnglats(0);
        Location arriveInfo = bizOrderResponse.getElnglats(0);
        LatLonPoint startPoint = new LatLonPoint(Double.valueOf(selfInfo.getLat()), Double.valueOf(selfInfo.getLng()));//起点，
        LatLonPoint endPoint = new LatLonPoint(Double.valueOf(arriveInfo.getLat()), Double.valueOf(arriveInfo.getLng()));//终点，
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                startPoint, endPoint);
        // 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,
                RouteSearch.DrivingDefault,
                null,
                null,
                "");
        // 异步路径规划驾车模式查询
        mRouteSearch.calculateDriveRouteAsyn(query);
    }


    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
        if (errorCode == 1000) {
            if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                if (driveRouteResult.getPaths().size() > 0) {
                    //    1.线路规划标记
                    isRouteSearched = true;

                    // 2.1线路规划
                    final DrivePath drivePath = driveRouteResult.getPaths()
                            .get(0);

                    mDrivingRouteOverlay = new ZMDrivingRouteOverlay(
                            mContext, aMap, drivePath,
                            driveRouteResult.getStartPos(),
                            driveRouteResult.getTargetPos());
                    mDrivingRouteOverlay.setThroughPointIconVisibility(true);
                    // 设置途径转弯处用户不可见,以免干扰途径点
                    mDrivingRouteOverlay.setNodeIconVisibility(false);
                    mDrivingRouteOverlay.removeFromMap();
                    mDrivingRouteOverlay.addToMap();
                    //  zoomToSpan();

                    // 2.2线路规划完成事件
//                    RxBus.getInstance().send(new RouteSearchCompleteEvent());

                    // 3.添加终点marker
                    //      addArriveStationMark();

                } else if (driveRouteResult != null && driveRouteResult.getPaths() == null) {
                    // no result
                    mOfficialCarScheduleMapView.routeResultFailure();
                }
            } else {
                // no result
                mOfficialCarScheduleMapView.routeResultFailure();
            }
        } else {
            // error
            mOfficialCarScheduleMapView.routeResultFailure();
        }
    }

    /**
     * 途经点markers聚合
     */
    public void zoomToSpan() {
        if (null != mDrivingRouteOverlay) {
            if (!isRouteSearched) {
                mDrivingRouteOverlay.zoomToSpan();
                isRouteSearched = true;
            }

        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void attachView(BaseView view) {
        if (view != null) {
            if (view instanceof OfficialCarScheduleMapView) {
                mOfficialCarScheduleMapView = (OfficialCarScheduleMapView) view;
            }
            if (view instanceof CommentOnDriverView) {
                mCommentOnDriverView = (CommentOnDriverView) view;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    class OfficialCarHandler extends Handler {

        public OfficialCarHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == WHAT_TCP_RESPONSE) {
                BizOrderResponse bizOrderResponse = (BizOrderResponse) msg.obj;
                updateUIByRideStatus(bizOrderResponse);
            }
        }
    }
}
